<template>
  <div class="login">
    <div class="box">
      <h2>用户登录</h2>
      <form>
        账号:
        <input v-model="username" type="text" placeholder="请输入账号" />
        <br><br>
        密码:
        <input v-model="password" type="password" placeholder="请输入密码" />
        <br><br>
        <el-button type="primary" @click="login">立即登录</el-button>
      </form>
      <div class="register">
        <span>没有账号?</span>
        <a href="#" @click.prevent="openRegisterModal">立即注册</a>
        <!-- <a href="http://localhost:8082/">我是管理员</a> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { API_BASE_URL } from '@/utils/constants'

const username = ref('')
const password = ref('')
const router = useRouter()

const login = async () => {
  if (username.value.length < 8) {
    alert('账号至少8位')
    return
  }
  if (password.value.length < 6) {
    alert('密码至少6位')
    return
  }

  try {
    const response = await axios.post(
      `${API_BASE_URL}/admin/login`,
      { adminUsername: username.value,adminPasswordHash: password.value }
    )

    console.log(response.data)
    alert(response.data.message)

    if (response.data.code === 1) {
      router.push('/dashboard') // 带斜杠的完整路径
    }
  } catch (error) {
    alert(error.response?.data?.message || '登录失败')
  }
}

const openRegisterModal = () => {
  // 触发自定义事件通知父组件打开模态框
  window.dispatchEvent(new CustomEvent('open-register-modal'))
}
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}
.login {
  position: absolute;
  right: 1%;
  top: 30%;
  width: 300px;
  height: 200px;
  /* flex: 1; */
  background-color: rgba(255, 255, 255, 0.5);
  padding: 40px;
}
h2 { 
  text-align: center;
  margin-bottom: 10px;
}
input { 
  width: 80%;
  height: 30px;
  border-radius: 10px;
  font-size: 18px;
}
button { 
  width: 150px;
  height: 30px;
  border-radius: 10px;
  font-size: 18px;
}
form{
  font-size: 18px;
  text-align: center;
}
.register {
  margin-top: 10px;
text-align: center;
}
</style>